package com.hnx.admin.aurora.aspects;

import com.alibaba.fastjson2.JSON;
import com.hnx.admin.aurora.annotation.Log;
import com.hnx.admin.aurora.api.log.LogWriter;
import com.hnx.admin.aurora.context.LogContext;
import com.hnx.admin.aurora.web.json.ResultJson;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/*
创建人： 倔强的头发
创建时间：2025/6/22
功能描述:

*/
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {
    private final LogWriter logWriter;
    /** 计算操作消耗时间 */

    /**
     * 处理请求前执行
     */
    @Before(value = "@annotation(controllerLog)")
    public void boBefore(JoinPoint joinPoint, Log controllerLog)
    {
        LogContext.setTime(System.currentTimeMillis());
    }
    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "json")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, ResultJson json)
    {
        logWriter.logHandler(joinPoint,controllerLog, JSON.toJSONString(json),0);
    }
    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e)
    {
        logWriter.logHandler(joinPoint,controllerLog, e.getMessage(),1);
    }
}
